package com.base.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.springframework.util.StringUtils;

import com.lovenote.common.global.GlobalDefine;

/**
 * File upload util class
 * 
 * @author Administrator
 *
 */
public class FileUploadUtil {
	
	/**
	 * Generate a new file name
	 * @return
	 */
	public static String generateNewFileName () {
		return UuidUtils.compressedUuid();
	}
	
	/**
	 * Generate save path
	 * @return
	 */
	public static String generateSavePath () {
		// Set the path format
		DateFormat format = new SimpleDateFormat("yyyy/MM/dd/");
		return format.format(new Date()); 
	}
	
	/**
	 *  Check file if is a image by InputStream
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	public static String isImage (InputStream input) throws IOException {
		// Get image extension
		String extension = getImageType(input);
		if (!StringUtils.isEmpty(extension)) {
			for (String type : GlobalDefine.UPLOAD_FILE_TYPE.IMAGE) {
				if (type.equals(extension)) {
					// It's an image
					return type;
				}
			}
		}
		return null;
	}
	
	/**
	 * Get image type by inputStream
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String getImageType (InputStream input) throws IOException {
		// Create an image input stream
		ImageInputStream iis = null;
		iis = ImageIO.createImageInputStream(input);
		// Find all image readers that recognize the image format
		Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
		if (!iter.hasNext()) {
			// It's not a image
			return null;
		}
		// Get the first reader
		ImageReader reader = iter.next();
		// Close the stream
		iis.close();
		return reader.getFormatName().toLowerCase();
	}
	
	/**
	 * Check if directory exists, if not exists create it
	 */
	public static void checkOrCreateFilePath (String directory) {
		File file = new File(directory);
		if (!file.exists()) {
			// Create directories
			file.mkdirs();
		}
	}
	
}
